<template>
  <div class="applications-container">
    <!-- 顶部统计卡片 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-number">{{ stats.total }}</div>
        <div class="stat-label">{{ $t('applications.allApplications') }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ stats.reviewing }}</div>
        <div class="stat-label">{{ $t('applications.platformReviewing') }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ stats.recommended }}</div>
        <div class="stat-label">{{ $t('applications.recommendedToEnterprise') }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ stats.unmatched }}</div>
        <div class="stat-label">{{ $t('applications.notMatching') }}</div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-item">
        <label>{{ $t('applications.statusFilter') }}</label>
        <el-select v-model="selectedStatus" :placeholder="$t('applications.allStatus')" @change="handleStatusChange" clearable>
          <el-option :label="$t('applications.allStatus')" value=""></el-option>
          <el-option :label="$t('applications.platformReviewingStatus')" value="platform_reviewing"></el-option>
          <el-option :label="$t('applications.recommendedToEnterpriseStatus')" value="recommended_to_enterprise"></el-option>
          <el-option :label="$t('applications.notMatchingStatus')" value="not_matching"></el-option>
        </el-select>
      </div>
      <div class="filter-actions">
        <el-button @click="resetFilters" size="small">{{ $t('applications.reset') }}</el-button>
        <el-button @click="loadApplications" :loading="loading" size="small" type="primary">
          <i class="el-icon-refresh"></i>
          {{ $t('applications.refresh') }}
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <div class="table-header">
        <h3>{{ $t('applications.applicationRecords') }}</h3>
        <div class="table-info">
          {{ $t('applications.totalRecords', { total: total }) }}
        </div>
      </div>
      <el-table 
        :data="applications" 
        style="width: 100%"
        v-loading="loading"
        :header-cell-style="{ 
          background: '#f5f5f5', 
          color: '#333', 
          fontWeight: '600',
          fontSize: '14px',
          padding: '12px 0'
        }"
        :cell-style="{ padding: '16px 0' }"
      >
        <el-table-column prop="applicationId" :label="$t('applications.applicationId')" width="100">
          <template #default="scope">
            <div class="id-cell">
              {{ scope.row.applicationId }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="demandInfo.title" :label="$t('applications.demandTitle')" min-width="200">
          <template #default="scope">
            <div class="title-cell">
              {{ scope.row.demandInfo?.title || scope.row.demandTitle || scope.row.title }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="demandInfo.enterpriseInfo.companyFullName" :label="$t('applications.companyName')" min-width="200">
          <template #default="scope">
            <div class="company-cell">
              {{ scope.row.demandInfo?.enterpriseInfo?.companyFullName || scope.row.enterpriseName || scope.row.companyName }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="demandInfo.salaryRange" :label="$t('applications.salaryRange')" width="120">
          <template #default="scope">
            <div class="salary-cell">
              {{ scope.row.demandInfo?.salaryRange || $t('applications.salaryNegotiable') }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="demandInfo.workLocation" :label="$t('applications.workLocation')" width="120">
          <template #default="scope">
            <div class="location-cell">
              {{ scope.row.demandInfo?.workLocation || $t('applications.locationNotSpecified') }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="applicationTime" :label="$t('applications.applicationTime')" width="120">
          <template #default="scope">
            <div class="time-cell">
              {{ formatDate(scope.row.applicationTime || scope.row.applyTime || scope.row.apply_time) }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="applicationStatus" :label="$t('applications.currentStatus')" width="150">
          <template #default="scope">
            <div class="status-cell">
              <div class="status-text" :class="'status-' + getStatusClass(scope.row.applicationStatus)">
                {{ getStatusText(scope.row.applicationStatus) }}
              </div>
              <div v-if="scope.row.rejectionReason" class="status-reason">
                {{ $t('applications.reason') }}: {{ scope.row.rejectionReason }}
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 空状态 -->
      <div v-if="!loading && applications.length === 0" class="empty-state">
        <div class="empty-icon">📋</div>
        <div class="empty-text">{{ $t('applications.noApplicationRecords') }}</div>
        <div class="empty-desc">{{ $t('applications.noApplicationDescription') }}</div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">
          {{ $t('applications.showingRecords', { 
            start: (currentPage - 1) * pageSize + 1, 
            end: Math.min(currentPage * pageSize, total), 
            total: total 
          }) }}
        </div>
        <div class="pagination-controls">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { studentApi } from '../../api/index.js'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'

// 使用i18n
const { t } = useI18n()

// 响应式数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const applications = ref([])
const loading = ref(false)
const selectedStatus = ref('') // 选中的状态筛选
const stats = ref({
  total: 0,
  reviewing: 0,
  recommended: 0,
  unmatched: 0
})

// 加载申请记录
const loadApplications = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 添加状态筛选参数
    if (selectedStatus.value) {
      params.status = selectedStatus.value
    }
    
    const response = await studentApi.getApplications(params)
    
    if (response.code === 200) {
      // 根据API响应格式处理数据
      applications.value = response.data.applications || []
      total.value = response.data.pagination?.totalCount || 0
      
      // 计算统计数据
      calculateStats()
    } else {
      ElMessage.error(response.message || t('applications.getApplicationsFailed'))
    }
  } catch (error) {
    console.error('获取申请记录失败:', error)
    ElMessage.error(t('applications.getApplicationsFailed'))
  } finally {
    loading.value = false
  }
}

// 计算统计数据
const calculateStats = () => {
  stats.value.total = applications.value.length
  stats.value.reviewing = applications.value.filter(app => 
    app.applicationStatus === 'platform_reviewing' || app.applicationStatus === 'submitted'
  ).length
  stats.value.recommended = applications.value.filter(app => 
    app.applicationStatus === 'recommended_to_enterprise'
  ).length
  stats.value.unmatched = applications.value.filter(app => 
    app.applicationStatus === 'not_matching'
  ).length
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取状态显示文本
const getStatusText = (status) => {
  const statusMap = {
    'submitted': t('applications.statusSubmitted'),
    'platform_reviewing': t('applications.statusPlatformReviewing'),
    'recommended_to_enterprise': t('applications.statusRecommendedToEnterprise'),
    'not_matching': t('applications.statusNotMatching')
  }
  return statusMap[status] || status
}

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    'submitted': 'reviewing',
    'platform_reviewing': 'reviewing',
    'recommended_to_enterprise': 'recommended',
    'not_matching': 'unmatched'
  }
  return statusMap[status] || 'reviewing'
}

// 处理状态筛选变化
const handleStatusChange = () => {
  currentPage.value = 1 // 重置到第一页
  loadApplications()
}

// 重置筛选条件
const resetFilters = () => {
  selectedStatus.value = ''
  currentPage.value = 1
  loadApplications()
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  loadApplications()
}

// 组件挂载时加载申请记录
onMounted(() => {
  loadApplications()
})
</script>

<style scoped>
.applications-container {
  width: 100%;
  height: 100%;
  padding: 30px;
  background: transparent;
  overflow-y: auto;
}

/* 统计卡片区域 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 40px;
}

.stat-card {
  background: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 24px 20px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.stat-number {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.stat-label {
  font-size: 0.9rem;
  color: #666;
  font-weight: 500;
}

/* 筛选区域 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-item label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.filter-item .el-select {
  min-width: 150px;
}

.filter-actions {
  display: flex;
  gap: 12px;
}

/* 表格区域 */
.table-section {
  background: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  background: #f8f9fa;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.table-info {
  font-size: 14px;
  color: #666;
}

/* 表格单元格样式 */
.title-cell,
.company-cell,
.time-cell {
  font-size: 14px;
  color: #333;
  line-height: 1.4;
}

.id-cell {
  font-weight: 600;
  color: #409eff;
  font-family: 'Courier New', monospace;
}

.salary-cell {
  font-weight: 500;
  color: #67c23a;
}

.location-cell {
  color: #666;
  font-size: 0.9rem;
}

.status-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.status-text {
  font-size: 14px;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
  width: fit-content;
}

.status-reason {
  font-size: 12px;
  color: #666;
  line-height: 1.3;
}

/* 状态颜色 */
.status-submitted {
  color: #f57c00;
  background: #fff3e0;
}

.status-reviewing {
  color: #1976d2;
  background: #e3f2fd;
}

.status-recommended {
  color: #388e3c;
  background: #e8f5e8;
}

.status-unmatched {
  color: #d32f2f;
  background: #ffebee;
}

/* 分页区域 */
.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-top: 1px solid #e0e0e0;
}

.pagination-info {
  font-size: 14px;
  color: #666;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #666;
}

.empty-desc {
  font-size: 14px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .applications-container {
    padding: 20px;
  }
  
  .stats-section {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .stat-card {
    padding: 16px 12px;
  }
  
  .stat-number {
    font-size: 1.5rem;
  }
  
  .filter-section {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .filter-item {
    justify-content: space-between;
  }
  
  .filter-actions {
    justify-content: center;
  }
  
  .table-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  /* 在小屏幕上隐藏一些列 */
  .el-table .el-table__cell:nth-child(1), /* 申请ID */
  .el-table .el-table__cell:nth-child(4), /* 薪资范围 */
  .el-table .el-table__cell:nth-child(5) { /* 工作地点 */
    display: none;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 15px;
  }
}

@media (max-width: 480px) {
  .stats-section {
    grid-template-columns: 1fr;
  }
}
</style>